package constant.milk.cashbook.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import constant.milk.cashbook.R;
import constant.milk.cashbook.SuperActivity;
import constant.milk.cashbook.asset.NameActivity;
import constant.milk.cashbook.database.DbAdapter;
import constant.milk.cashbook.database.DbHelper;
import constant.milk.cashbook.tip.TipInfoActivity;
import constant.milk.cashbook.tip.TipMap;
import constant.milk.cashbook.util.MilkUtil;

public class DataBankUpActivity extends SuperActivity
{
	public static final String FILE_NAME = "HouseCashBook";
	public static final int NAME_REQUEST_CODE = 0;
	
	public static final int AUTO_BACKUP_DATA_COUNT = 31;
	
	private View nameView;
	private TextView nameTextView;
	
	private Button saveButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.data_bankup_activity);
		
		setTitle("데이터백업");
		
		setFindViewId();
		setOnClick();
		setData();
	}

	@Override
	protected void setFindViewId()
	{
		nameView = findViewById(R.id.dataBankUpNameView);
		nameTextView = (TextView) findViewById(R.id.dataBankUpNameTextView);
		
		saveButton = (Button) findViewById(R.id.saveButton);
	}

	@Override
	protected void setOnClick()
	{
		nameView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, NameActivity.class);
				intent.putExtra(NameActivity.NAME_DATA, nameTextView.getText().toString());
				startActivityForResult(intent, NAME_REQUEST_CODE);
			}
		});
		
		saveButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (setCheckData())
				{
					return;
				}
				
				if (setSaveData())
				{
					MilkUtil.showDialogFinish(superContext, "확인", "데이터 저장에 성공하였습니다.");
				}
				else
				{
					MilkUtil.showDialog(superContext, "실패", "컴퓨터에 연결을 빼고 하시거나, 잠시후 다시해 주세요.");
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH);
		int day = cal.get(Calendar.DAY_OF_MONTH);
		String time = cal.get(Calendar.HOUR) + "" + cal.get(Calendar.MINUTE) + "" + cal.get(Calendar.SECOND);
		
		String date = MilkUtil.getDate(year, month+1, day);
		
		date = date.replace(" ", "");
		
		String fileName = FILE_NAME + "_" + date + "_" + time;
		
		nameTextView.setText(fileName);
	}
	
	private boolean setSaveData()
	{
		DbAdapter adapter = DbAdapter.getInstance();
		String path = adapter.getDbPath(superContext);
		adapter.close();
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try
		{
			File readfile = new File(path);
			
			if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
			{
				return false;
			}
			
			fis = new FileInputStream(readfile);
			
			File directory = new File(Environment.getExternalStorageDirectory() + "/" 
										+ DataMainActivity.dirName);
			
			if (!directory.exists())
			{
				directory.mkdir();
			}
			
			String directoryPath = directory.getPath();
			
			File writefile = new File(directoryPath + "/" + nameTextView.getText().toString() + ".db");
			
			fos = new FileOutputStream(writefile);
			
			byte [] buffer = new byte[1024];
			
			int bufBytes = 0;
			while ((bufBytes = fis.read(buffer)) != -1) 
			{
				fos.write(buffer, 0, bufBytes);
			}
			fos.flush();
			
		} catch (Exception e)
		{
			return false;
		} finally {
			try
			{
				if (fis != null) fis.close();
				if (fos != null) fos.close();
			} catch (IOException e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	/**
	 * 테이터가 제대로 있는지 확인한다.
	 */
	private boolean setCheckData()
	{
		String name = nameTextView.getText().toString();
		
		if (name.equals("") || name.length() < 1)
		{
			MilkUtil.showDialog(superContext, "확인", "이름을 입력해주세요.");
			return true;
		}
		
		return false;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
		
		if (requestCode == NAME_REQUEST_CODE)
		{
			String str = data.getStringExtra(NameActivity.NAME_DATA);
			nameTextView.setText(str);
		}
	}
	
	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(superContext, TipInfoActivity.class);
		intent.putExtra(TipInfoActivity.TIP_ID, TipMap.TIP_DATA_BACKUP);
		startActivity(intent);
	}

}
